package com.onpositive.gamemaker.visualizer.swt;


import com.onpositive.gamemaker.core.CompositeSprite;
import com.onpositive.gamemaker.core.GameLevel;
import com.onpositive.gamemaker.core.GraphicDevice;
import com.onpositive.gamemaker.visualizer.HexagonMath;
import com.onpositive.gamemaker.visualizer.ILevelVisualizer;
import com.onpositive.gamemaker.visualizer.ISpriteProvider;

public class BasicLevelVisualizer implements ILevelVisualizer
{
	
	private static final int DEFAULT_CELL_DIAMETER = 40;
	
	protected final GraphicDevice gc;
	protected final int cellDiameter;
	protected final int yIncrement;

	protected ISpriteProvider spriteProvider;
	

	public BasicLevelVisualizer(GraphicDevice gc, ISpriteProvider spriteProvider)
	{
		this.gc = gc;
		this.spriteProvider = spriteProvider;
		cellDiameter = getCellDiameter();
		yIncrement = (int) Math.round(HexagonMath.TRIANGLE_MULTIPLIER * cellDiameter / 2);
	}
	
	protected int getCellDiameter()
	{
		return DEFAULT_CELL_DIAMETER;
	}

	
	public void visualizeLevel(GameLevel level)
	{
		int width = level.getWidth();
		int height = level.getHeight();
		visualizeLevel(level, 0,0 , width, height);
	}

	@Override
	public void visualizeLevel(GameLevel level, int x, int y, int width, int height)
	{
		int startXcell = Math.min(x / (cellDiameter + cellDiameter / 2), level.getWidth() - 1);
		int startYcell = Math.min(y / yIncrement, level.getHeight() - 1);
		int endXcell = Math.min((x + width) / (cellDiameter + cellDiameter / 2), level.getWidth() - 1);
		int endYcell = Math.min(((y + height) / yIncrement) + 1, level.getHeight() - 1);
		
		if (startYcell > 0)
			startYcell -= 1;
		int currenty = (startYcell * yIncrement)/* - y*/;
		int xstart = 0;
		for (int i = startYcell; i < endYcell; i++)
		{
			xstart = cellDiameter / 4 * 3 * (i % 2);
			for (int j = startXcell; j <= endXcell; j++)
			{
				CompositeSprite sprites = spriteProvider.getSprites(j,i);
				sprites.paint(xstart + j * (cellDiameter + cellDiameter / 2)/* - x*/,currenty,cellDiameter,cellDiameter,gc);
			}
			currenty += yIncrement;
		}
	}
	
	/**
	 * @return the spriteProvider
	 */
	public ISpriteProvider getSpriteProvider()
	{
		return spriteProvider;
	}

	/**
	 * @param spriteProvider the spriteProvider to set
	 */
	public void setSpriteProvider(ISpriteProvider spriteProvider)
	{
		this.spriteProvider = spriteProvider;
	}

}
